package com.zaofan.service;

import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.zaofan.bean.Account;
import com.zaofan.bean.Dynamic;
import com.zaofan.bean.DynamicDTO;
import com.zaofan.bean.Topic;
import com.zaofan.bean.UserImage;
import com.zaofan.constant.StateConstant;
import com.zaofan.constant.UrlConstant;
import com.zaofan.dao.TopicDao;
import com.zaofan.exception.ServiceException;
import com.zaofan.utils.C3p0DataSourceUtils;
import com.zaofan.utils.SqlBuilderUtils;
import com.zaofan.utils.WebUtils;

public class TopicService {
	private TopicDao topicDao = new TopicDao();
	private AccountService accountService = new AccountService();
	private DynamicService dynamicService = new DynamicService();

	public void delete(Topic topic) {
		topicDao.del(topic);
	}

	public void add(Topic topic) throws ServiceException {
		if (WebUtils.isEmpty(topic.getTitle())) {
			throw new ServiceException("请输入话题标题");
		}
		if (WebUtils.isEmpty(topic.getDes())) {
			throw new ServiceException("请输入话题简单描述");
		}
		if (WebUtils.isEmpty(topic.getContent())) {
			throw new ServiceException("请输入话题内容");
		}
		if (WebUtils.isEmpty(topic.getImage())) {
			throw new ServiceException("请选择话题的图片");
		}
		if (WebUtils.isEmpty(topic.getBigImage())) {
			throw new ServiceException("请选择话题的大图片");
		}
		if (topic.getType() == 0) {
			throw new ServiceException("请选择话题类型");
		}
		topic.setCount(0);
		topic.setPraise(0);
		topic.setFinish(0);
		topic.setAddTime(new Date());
		topic.setState(StateConstant.STATE_SHOW);
		topicDao.add(topic);
	}

	public void update(Topic topic) {
		topicDao.update(topic);
	}

	public void updateTopic(Topic topic) throws ServiceException {
		if (WebUtils.isEmpty(topic.getId())) {
			throw new ServiceException("请输入id");
		}
		Topic target = this.findById(topic.getId());
		if (target == null) {
			throw new ServiceException("请输入id");
		}
		if (!WebUtils.isEmpty(topic.getTitle())) {
			target.setTitle(topic.getTitle());
		}
		if (!WebUtils.isEmpty(topic.getDes())) {
			target.setDes(topic.getDes());
		}
		if (!WebUtils.isEmpty(topic.getContent())) {
			target.setContent(topic.getContent());
		}
		if (!WebUtils.isEmpty(topic.getImage())) {
			target.setImage(topic.getImage());
		}
		if (!WebUtils.isEmpty(topic.getBigImage())) {
			target.setBigImage(topic.getBigImage());
		}
		if (topic.getType() != 0) {
			target.setType(topic.getType());
		}
		topicDao.update(target);
	}

	public List<Topic> findAll(Map<String, Object> params) {
		List<Topic> data = topicDao.findAll(params);
		if (data == null) {
			data = new ArrayList<>();
		}
		return data;
	}

	public Long count(Map<String, Object> params) {
		return topicDao.count(params);
	}

	public Topic findById(int id) {
		Map<String, Object> params = new HashMap<>();
		params.put("id", id + "");
		return topicDao.findOne(params);
	}

	public List<Topic> findHotTopic(Integer begin, Integer end) {
		Map<String, Object> params = new HashMap<>();
		params.put("begin", begin + "");
		params.put("end", end + "");
		params.put("finish", 0);
		params.put("state", 0);
		params.put("order", " by type desc,count desc ,praise desc");
		List<Topic> datas = this.findAll(params);
		if (datas != null) {
			for (Topic topic : datas) {
				topic.setBigImage(UrlConstant.HOST_URL + topic.getBigImage());
				topic.setImage(UrlConstant.HOST_URL + topic.getImage());
			}
		}
		return datas;
	}

	public void praiseTopic(Integer userId, Integer id) throws ServiceException {
		Account user = accountService.findById(userId);
		if (user == null) {
			throw new ServiceException("您还未登录,请重新登录试试!!!");
		}
		Topic topic = findById(id);
		if (topic == null) {
			throw new ServiceException("话题不存在或已被删除,请刷新试试!!!");
		}
		if (topic.getFinish() == 1) {
			throw new ServiceException("话题已结束,无法进行评论,请刷新试试!!!");
		}
		topic.setPraise(topic.getPraise() + 1);
		Dynamic dynamic = new Dynamic();
		dynamic.setAddTime(new Date());
		dynamic.setContent("");
		dynamic.setCount(0);
		dynamic.setIsDelete(0);
		dynamic.setPraise(0);
		dynamic.setType(1);
		dynamic.setUserId(user.getId());
		dynamic.setTopicId(topic.getId());
		dynamic.setReplyType(0);

		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			try {
				connection.setAutoCommit(false);
				QueryRunner runner = new QueryRunner();
				String sql = SqlBuilderUtils.builderInsertSql(Dynamic.class, dynamic);
				runner.update(connection, sql);
				sql = SqlBuilderUtils.builderUpdateSql(Topic.class, topic);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
				throw new ServiceException("发布失败!!!");
			} finally {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServiceException("发布失败!!!");
		}
	}

	public Map<String, Object> getTopicDetail(int id) {
		Map<String, Object> data = new HashMap<>();
		Topic topic = this.findById(id);
		topic.setBigImage(UrlConstant.HOST_URL + topic.getBigImage());
		topic.setImage(UrlConstant.HOST_URL + topic.getImage());
		data.put("topic", topic);
		List<DynamicDTO> dtos = dynamicService.findByTopicIdWithOther(0 + "", "10", id + "", 1 + "", null);
		data.put("reply", dtos);
		return data;
	}

	public void replyTopic(DynamicDTO dto) throws ServiceException {
		Account user = accountService.findById(dto.getUserId());
		if (user == null) {
			throw new ServiceException("您还未登录,请重新登录试试!!!");
		}
		Topic topic = findById(dto.getId());
		if (topic == null) {
			throw new ServiceException("话题不存在或已被删除,请刷新试试!!!");
		}
		if (topic.getFinish() == 1) {
			throw new ServiceException("话题已结束,无法进行评论,请刷新试试!!!");
		}
		topic.setCount(topic.getCount() + 1);
		Dynamic dynamic = new Dynamic();
		dynamic.setAddTime(new Date());
		dynamic.setContent(WebUtils.filter(dto.getContent()));
		dynamic.setCount(0);
		dynamic.setIsDelete(0);
		dynamic.setPraise(0);
		dynamic.setType(1);
		dynamic.setUserId(dto.getUserId());
		dynamic.setTopicId(topic.getId());
		dynamic.setReplyType(1);
		dynamic.setAddress(dto.getAddress());
		
		Connection connection = C3p0DataSourceUtils.getConnection();
		try {
			try {
				connection.setAutoCommit(false);
				QueryRunner runner = new QueryRunner();
				String sql = SqlBuilderUtils.builderInsertSql(Dynamic.class, dynamic);
				runner.update(connection, sql);
				int id = 0;
				try {
					Long t = (Long) runner.query(connection, "SELECT LAST_INSERT_ID()", new ScalarHandler<Long>());
					id = t.intValue();
				} catch (Exception e) {
					BigInteger t = (BigInteger) runner.query(connection, "SELECT LAST_INSERT_ID()",
							new ScalarHandler<BigInteger>());
					id = t.intValue();
				}
				if (dto.getImage() != null && dto.getImage().length() > 0) {
					UserImage images;
					for (String image : dto.getImage().split(",")) {
						images = new UserImage();
						images.setType(0);
						images.setDynamicId(id);
						images.setImage(image);
						images.setUserId(dto.getUserId());
						sql = SqlBuilderUtils.builderInsertSql(UserImage.class, images);
						runner.update(connection, sql);
					}
				}
				sql = SqlBuilderUtils.builderUpdateSql(Topic.class, topic);
				runner.update(connection, sql);
				connection.commit();
			} catch (Exception e) {
				e.printStackTrace();
				connection.rollback();
				throw new ServiceException("发布失败!!!");
			} finally {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new ServiceException("发布失败!!!");
		}
	}

}
